<?php

namespace app\admin\controller;

use app\admin\service\RatingScaleCloudService;
use app\admin\service\RatingScaleImportService;
use app\BaseController;
use app\model\RatingScaleCloudModel;
use app\model\RatingScaleDownloadLogModel;
use app\model\RatingScaleModel;
use think\App;

class RatingScaleCloud extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new RatingScaleCloudModel();
    }

    /**
     * 云端量表列表
     * @return false|string
     */
    public function list(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            }else{
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            $query = $this->mode->where($where);
            $data = $query->with([
                'user',
                'RatingScale' => function($query) {
                    $query->with(['RatingScaleQuestion']);
                }
            ])->paginate($param['pageSize'])->toArray();
            $cloud_id = array_column($data['data'], 'id');
            $RatingScaleDownloadLogModel = new RatingScaleDownloadLogModel();
            $ids = $RatingScaleDownloadLogModel->where([
                ['uid','=',$this->userData['id']],
                ['cloud_id','in',$cloud_id]
            ])->column('cloud_id');
            foreach ($data['data'] as &$item) {
                $item['status'] = 1;
                if ($item['uid'] == $this->userData['id']){
                    $item['status'] = 2;
                }elseif (in_array($item['id'],$ids)){
                    $item['status'] = 3;
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增云端量表
     * @return false|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'rating_scale|量表' => 'require',
                'download_price|下载价格' => 'require',
            ]);
            $cloudData = [];
            foreach ($param['rating_scale'] as $item) {
                $cloudData[] = [
                    'uid' => $this->userData['id'],
                    'rating_scale_id' => $item['rating_scale_id'],
                    'name' => $item['name']??'',
                    'download_price' => $param['download_price'],
                    'time' => time()
                ];
            }
            if (count($cloudData)){
                $this->mode->insertAll($cloudData);
            }
            return success([],'添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增云端量表-本地上传分享
     * @return false|string
     */
    public function localAdd(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'data|数据' => 'require'
            ]);
            $RatingScaleImportService = new RatingScaleImportService($this->app);
            foreach ($param['data'] as $item) {
                if (!$RatingScaleImportService->import('.'.$item['file'], [
                    'company_id' => $this->userData['company_id'],
                    'areas_id' => $this->userData['areas_id'],
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'name' => $item['name'],
                    'cover' => $item['cover']??'',
                    'download_price' => $item['download_price']??0,
                ],2)) throw new \Exception($RatingScaleImportService->message.'line:'.$RatingScaleImportService->line);
            }
            $this->mode->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除云端量表
     * @return false|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $this->mode->where('id','=',$id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 下载
     * @return false|string
     */
    public function download(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $RatingScaleCloudService = new RatingScaleCloudService($this->app);
            if (is_array($id)){
                foreach ($id as $item){
                    if (!$RatingScaleCloudService->download($item,$this->userData)) throw new \Exception($RatingScaleCloudService->message);
                }
            }else{
                if (!$RatingScaleCloudService->download($id,$this->userData)) throw new \Exception($RatingScaleCloudService->message);
            }
            return success([],'下载成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 已下载列表
     * @return bool|string
     */
    public function downloadList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            $RatingScaleDownloadLogModel = new RatingScaleDownloadLogModel();
            $list = $RatingScaleDownloadLogModel->where($where)
                ->with([
                    'Unit',
                    'RatingScaleCloudModel' => function($query){
                        $query->with('RatingScale');
                    }
                ])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 已下载-删除
     * @return bool|string
     */
    public function downloadDel(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $RatingScaleDownloadLogModel = new RatingScaleDownloadLogModel();
            $RatingScaleModel = new RatingScaleModel();
            if (is_array($id)){
                $rating_scale_id = $RatingScaleDownloadLogModel->where('id','in',$id)->column('rating_scale_id');
                $RatingScaleDownloadLogModel->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $RatingScaleModel->where('id','in',$rating_scale_id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $info = $RatingScaleDownloadLogModel->find($id);
                if (!$info) throw new \Exception('参数错误!');
                $info->is_del = 1;
                $info->del_time = time();
                $info->save();
                $info2 = $RatingScaleModel->find($info['rating_scale_id']);
                $info2->is_del = 1;
                $info2->del_time = time();
                $info2->save();
            }
            $this->mode->commit();
            return success();
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}
